package com.yonyou.ucf.mdf.app.isvdxq.interceptor;

//import com.yonyou.ucf.mdd.ext.core.AppContext;

import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.MyTokenService;
import com.yonyoucloud.iuap.ucf.mdd.starter.core.UCFCoreProperties;
import com.yonyoucloud.iuap.ucf.mdd.starter.core.module.mvc.interceptor.AllowConfOriginCorsInterceptor;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

@Component
@RequiredArgsConstructor
public class DXQWebMvcConfigurer implements WebMvcConfigurer {
    private final UCFCoreProperties properties;
    private final DXQHeaderInterceptor headerInterceptor;

    @Autowired
    private MyTokenService myTokenService;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("[isv2-GDGY01]启动");
        registry.addInterceptor(headerInterceptor)
                .addPathPatterns(DxqConfig.pre_apiUrl+"/**")
                .addPathPatterns(DxqConfig.pre_pcUrl+"/**")
                .addPathPatterns(DxqConfig.DXQ_prefix+"/**");
        setISVAllowCorsDomain();
        registry.addInterceptor(new AllowConfOriginCorsInterceptor(properties))
                .addPathPatterns("/**");
    }

    private void setISVAllowCorsDomain() {
        String[] allowCorsDomains = properties.getAllowCorsDomains();
        String[] ISVAllowCorsDomains = null;
        String allowCrossDomain = myTokenService.getProperty("allowCross.Domains");
        if (StringUtils.isNotBlank(allowCrossDomain)) {
            int length = allowCorsDomains.length + 2;
            ISVAllowCorsDomains = Arrays.copyOf(allowCorsDomains,length);
            ISVAllowCorsDomains[length-2] = allowCrossDomain;
            ISVAllowCorsDomains[length-1] = "yonisv.com";
        }else{
            int length = allowCorsDomains.length + 1;
            ISVAllowCorsDomains = Arrays.copyOf(allowCorsDomains,length);
            if(length >= 2) {
                ISVAllowCorsDomains[length-1] = "yonisv.com";
            }
        }
        if(ISVAllowCorsDomains == null) {
            properties.setAllowCorsDomains(ISVAllowCorsDomains);
        }
    }

}
